package com.yami.shop.rights.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.RightsType;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.QrcodeTicket;
import com.yami.shop.common.util.IdUtil;
import com.yami.shop.mystery.common.dao.ActivityPresellQualificationMapper;
import com.yami.shop.mystery.common.model.ActivityPresellQualification;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import com.yami.shop.rights.common.dao.PersonRightsMapper;
import com.yami.shop.rights.common.dto.PersonRightsDto;
import com.yami.shop.rights.common.model.PersonRights;
import com.yami.shop.rights.common.model.ProdRights;
import com.yami.shop.rights.common.model.ProdRightsPreemption;
import com.yami.shop.rights.common.service.PersonRightsService;
import com.yami.shop.rights.common.vo.PersonRightsVo;
import com.yami.shop.rights.common.vo.PersonnftRightsVo;
import com.yami.shop.rights.common.vo.ProdRightsVo;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.QrcodeTicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PersonRightsServiceImpl extends ServiceImpl<PersonRightsMapper, PersonRights> implements PersonRightsService {

    @Autowired
    private PersonRightsMapper personRightsMapper;
    @Autowired
    private QrcodeTicketService qrcodeTicketService;
    @Autowired
    private IdUtil idUtil;
    @Autowired
    private ProdRightsPreemptionServiceImpl prodRightsPreemptionService;
    @Autowired
    private ProductService productService;
    @Autowired
    private MysteryBoxService mysteryBoxService;
    @Autowired
    private ActivityPresellQualificationMapper activityPresellQualificationMapper;

    @Override
    public List<ProdRights> listUserByRightsIds(String userId, String rightsIds) {
        List<String> rightsIdList = Arrays.asList(rightsIds.split(","));
        return personRightsMapper.listUserByRightsIds(userId,rightsIdList);
    }

    @Override
    public ProdRightsVo getProdRightsById(Long personRightsId ,String userId) {
        PersonnftRightsVo prodRightsById = personRightsMapper.getProdRightsById(personRightsId);
        // 保存二维码信息
        JSONObject json = new JSONObject();
        json.put("tokenId",prodRightsById.getTokenId());
        json.put("rightsId",prodRightsById.getRightsId());
        json.put("type",prodRightsById.getType());
        json.put("userId",userId);
        json.put("rightsExternalDataId",prodRightsById.getRightsExternalDataId());
        json.put("personRightsId",prodRightsById.getPersonRightsId());
        json.put("expireTime",DateUtil.offsetMinute(new Date(),3));

        String ticket = idUtil.nextShortId();
        QrcodeTicket qrcodeTicket = new QrcodeTicket();
        qrcodeTicket.setContent(json.toString());
        qrcodeTicket.setCreateTime(new Date());
        qrcodeTicket.setExpireTime(DateUtil.offsetMinute(new Date(),3));
        qrcodeTicket.setType(2);
        qrcodeTicket.setTicket(ticket);
        qrcodeTicketService.save(qrcodeTicket);
        ProdRightsVo prodRightsVo = BeanUtil.copyProperties(prodRightsById, ProdRightsVo.class);
        JSONObject qrData = new JSONObject();
        qrData.put("qrCodeId",qrcodeTicket.getTicketId().toString());
        prodRightsVo.setQrCodeId(qrData.toJSONString());
        return prodRightsVo;
    }

    @Override
    public PersonnftRightsVo getProdRightsInfoById(Long personRightsId) {
        return personRightsMapper.getProdRightsById(personRightsId);
    }

    @Override
    public ProdRightsVo getProdInfoByPersonRightsId(Long personRightsId) {
        return personRightsMapper.getProdInfoByPersonRightsId(personRightsId);
    }

    @Override
    public List<PersonRightsDto> getPersonRightsByTokenId(String tokenId) {

        return personRightsMapper.getPersonRightsByTokenId(tokenId,"");
    }

    @Override
    public List<PersonRightsVo> getPersonRightsByRightsId(String tokenId) {
        List<PersonRightsVo> personRightsVos = new ArrayList<>();
        List<PersonRightsDto> personRightsByTokenId = personRightsMapper.getPersonRightsByTokenId(tokenId,"");
        // 补充商品信息
        for(PersonRightsDto personRightsDto : personRightsByTokenId){
            // 优先购权益
            if(RightsType.PREEMPTION_RIGHTS.value().equals(personRightsDto.getType())){
                // 获取 优先购绑定商品
                QueryWrapper<ProdRightsPreemption> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("rights_id",personRightsDto.getRightsId());
                queryWrapper.eq("status", 1);
                List<ProdRightsPreemption> list = prodRightsPreemptionService.list(queryWrapper);
                if(ObjectUtil.isNotEmpty(list)){
                    for (ProdRightsPreemption prodRightsPreemption : list){
                        PersonRightsVo personRightsVo = new PersonRightsVo();
                        QueryWrapper<ActivityPresellQualification> activityPresellQualificationQueryWrapper = new QueryWrapper<>();
                        activityPresellQualificationQueryWrapper.eq("source_id",personRightsDto.getId());
                        if("1".equals(prodRightsPreemption.getBlindType())){
                            // 获取商品信息
                            Product productInfo = productService.getProductInfo(prodRightsPreemption.getBlindId());
                            personRightsVo.setProdName(productInfo.getProdName()+"-优先购资格");
                            activityPresellQualificationQueryWrapper.eq("prod_id",prodRightsPreemption.getBlindId());
                        }else{
                            MysteryBox byId = mysteryBoxService.getById(prodRightsPreemption.getBlindId());
                            personRightsVo.setProdName(byId.getBoxName()+"-优先购资格");
                            activityPresellQualificationQueryWrapper.eq("box_id",prodRightsPreemption.getBlindId());
                        }
                        // 获取剩余次数
                        ActivityPresellQualification activityPresellQualification = activityPresellQualificationMapper.selectOne(activityPresellQualificationQueryWrapper);
                        personRightsVo.setTimes(activityPresellQualification.getTimes());
                        personRightsVo.setStatus(activityPresellQualification.getStatus());
                        personRightsVos.add(personRightsVo);
                    }
                }
            }
        }
        personRightsVos = personRightsVos.stream().sorted(Comparator.comparing(PersonRightsVo::getStatus)).collect(Collectors.toList());
        return personRightsVos;
    }

    @Override
    public List<PersonRightsVo> getPersonRightsByPersonRightsId(Long personRightsId) {
        List<PersonRightsVo> personRightsVos = new ArrayList<>();
        List<PersonRightsDto> personRightsByTokenId = personRightsMapper.getPersonRightsByPersonRightsId(personRightsId);
        // 补充商品信息
        for(PersonRightsDto personRightsDto : personRightsByTokenId){
            // 优先购权益
            if(RightsType.PREEMPTION_RIGHTS.value().equals(personRightsDto.getType())){
                // 获取 优先购绑定商品
                QueryWrapper<ProdRightsPreemption> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("rights_id",personRightsDto.getRightsId());
                queryWrapper.eq("status", 1);
                List<ProdRightsPreemption> list = prodRightsPreemptionService.list(queryWrapper);
                if(ObjectUtil.isNotEmpty(list)){
                    for (ProdRightsPreemption prodRightsPreemption : list){
                        PersonRightsVo personRightsVo = new PersonRightsVo();
                        QueryWrapper<ActivityPresellQualification> activityPresellQualificationQueryWrapper = new QueryWrapper<>();
                        activityPresellQualificationQueryWrapper.eq("source_id",personRightsDto.getId());
                        if("1".equals(prodRightsPreemption.getBlindType())){
                            // 获取商品信息
                            Product productInfo = productService.getProductInfo(prodRightsPreemption.getBlindId());
                            personRightsVo.setProdName(productInfo.getProdName()+"-优先购资格");
                            activityPresellQualificationQueryWrapper.eq("prod_id",prodRightsPreemption.getBlindId());
                        }else{
                            MysteryBox byId = mysteryBoxService.getById(prodRightsPreemption.getBlindId());
                            personRightsVo.setProdName(byId.getBoxName()+"-优先购资格");
                            activityPresellQualificationQueryWrapper.eq("box_id",prodRightsPreemption.getBlindId());
                        }
                        // 获取剩余次数
                        ActivityPresellQualification activityPresellQualification = activityPresellQualificationMapper.selectOne(activityPresellQualificationQueryWrapper);
                        personRightsVo.setTimes(activityPresellQualification.getTimes());
                        personRightsVo.setStatus(activityPresellQualification.getStatus());
                        personRightsVos.add(personRightsVo);
                    }
                }
            }
        }
        personRightsVos = personRightsVos.stream().sorted(Comparator.comparing(PersonRightsVo::getStatus)).collect(Collectors.toList());
        return personRightsVos;
    }

    @Override
    public Boolean getRightsStatusByPerson(String tokenId) {
        List<PersonRightsDto> personRightsByTokenId = personRightsMapper.getPersonRightsByTokenId(tokenId,"12");
        // 过滤异常状态的持仓权益
        List<PersonRightsDto> noStatusRights = personRightsByTokenId.stream().filter(s -> !"0".equals(s.getStatus())).collect(Collectors.toList());
        return noStatusRights.size() > 0;
    }

}
